﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Scheduler;
using  Agent.Messaging;
using System.Diagnostics;
using System.Threading;

namespace AgentLibrary
{
  public class SimpleAgent : ScheduledTaskAgent
  {
    MessageSender messageSender;
    MessageReceiver messageReceiver;
    DetailedLogger logger;

    protected override void OnInvoke(ScheduledTask Task)
    {
      if (Thread.CurrentThread.Name == null)
        Thread.CurrentThread.Name = "invoke thread";

      DetailedLogger.LogFileName = "AGENT_LOG_FILE.TXT";
      logger = new DetailedLogger("Agent");
      logger.AlwaysLogToDebugWindow = true;

      logger.Log("Starting up...");

      logger.Log("Creating toApp sender...");
      messageSender = new MessageSender("toApp");
      messageSender.Start();

      logger.Log("Creating toAgent receiver...");
      messageReceiver = new MessageReceiver("toAgent");
      messageReceiver.MessageReceived += receiver_MessageReceived;
      messageReceiver.Start();

      logger.Log("Sending message that we have started up");
      messageSender.SendMessage(DateTime.Now.ToLongTimeString() + ": + Agent starting up...");

      logger.Log("Sleeping for a few seconds Zzzzzz");
      Thread.Sleep(4000);

      messageSender.SendMessage(DateTime.Now.ToLongTimeString() + ": - Waking up... still sleepy... zzzzzz");

      logger.Log("Sleeping for a few seconds Zzzzzz");
      Thread.Sleep(4000);

      logger.Log("Zzz.... Waking up and about to shut down");

      messageSender.SendMessage(DateTime.Now.ToLongTimeString() + ": - Agent shutting down...");

      logger.Log("Stopping the sender");
      messageSender.Stop();

      logger.Log("Stopping the receiver");
      messageReceiver.Stop();

      logger.Log("Agent closing down...");

      DetailedLogger.Close();

      NotifyComplete();
    }

    void receiver_MessageReceived(object sender, MessageReceivedEventArgs e)
    {
      logger.Log("Received message " + e.Message + ", going to ack if we haven't been stopped");
      if (messageSender.CurrentState == SenderReceiverStateMachineState.Running)
      {
        try
        {
          logger.Log("We weren't stopped; acking the message " + e.Message);
          messageSender.SendMessage("$$ACK:" + e.Message);
        }
        catch { }
      }

      if (e.Message == "$$DELETE_LOG$$")
        DetailedLogger.DeleteLogFile();
      else if (e.Message == "$$THROW$$")
        throw new Exception("throwing because the sender told us to...");

      logger.Log("End of function");
    }
  }
}
